var e = require("./services/baseURL.js"), t = require("./utils/util.js");

App({
    onLaunch: function() {
        (0, t.getAuth)() && this.setGlobalData({
            hasToken: !0
        }), this.setLogin();
    },
    setLogin: function() {
        var e = (0, t.getUserInfo)();
        e && this.setGlobalData({
            userInfo: e
        });
    },
    onShow: function() {
        this.updateVersion();
    },

    
    updateVersion: function() {
        var e = wx.getUpdateManager();
        e.onCheckForUpdate(function(e) {
            console.log(e.hasUpdate);
        }), e.onUpdateReady(function() {
            wx.showModal({
                title: "更新提示",
                content: "新版本已经准备好，是否重启应用？",
                success: function(t) {
                    t.confirm && e.applyUpdate();
                }
            });
        }), e.onUpdateFailed(function() {});
    },
    setGlobalData: function(e) {
        for (var t in e) t in this.globalData && (this.globalData["".concat(t)] = e["".concat(t)]), 
        this.hasObserver(t) && this.observers[t](this.globalData["".concat(t)]);
    },
    tokenObserverHandle: function() {
        this.tokenObservers.forEach(function(e) {
            e();
        }), this.tokenObservers = [];
    },
    tokenObservers: [],
    addObserver: function(e, t) {
        this.observers[t] = e;
    },
    removeObserver: function(e) {
        this.hasObserver(e) && delete this.observers[e];
    },
    hasObserver: function(e) {
        return e in this.observers;
    },
    observers: {},
    globalData: {
        userInfo: !1,
        location: null,
        login: null,
        starship: -1,
        modal: !1,
        contact: "18144345267",
        hasToken: !1,
        isLock: !1,
        NODE_ENV: e.NODE_ENV,
        checkedService: []
    },
    getLogin: function() {
        var e = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0];
        return this.globalData.userInfo ? this.globalData.userInfo : !!e && void wx.navigateTo({
            url: "/pages/login/index"
        });
    },










  onLaunch: function (options) {
    this.globalData.userInfo = wx.getStorageSync('userInfo') || null;
    this.globalData.sessionId = wx.getStorageSync('sessionId') || '';
    this.globalData.openid = wx.getStorageSync('openid') || '';
    this.globalData.member_id = wx.getStorageSync('member_id') || '';
    this.globalData.user_id = wx.getStorageSync('user_id') || '';
    // mta.App.init({
    //   "appID": "500607409",
    // });
  },

  onShow(options) {
    this.globalData.scene = options.scene;
  },

  globalData: {
    userInfo: null, //用户信息
    sessionId: '', //session_id
    openid: '', //用户open_id
    scene: '', //场景值
    // hosts: "https://api.mengjukeji.com/201/BoxV2/",
    hosts: "https://oxx.chscq.com/",
    app_mini_id: 597,
  },

  /**
   * login
   */
  wxLogin: function (success, fail) {
    let that = this;
    wx.login({
      success: function (result) {
        wx.request({
          url: that.getApiUrl('xcxapi/login'),
          header: {
            "content-type": "application/x-www-form-urlencoded",
          },
          method: 'POST',
          data: {
            code: result.code,
            // app_mini_id: that.globalData.app_mini_id,
            // scene: that.globalData.scene,
          },
          success: function (res) {
            if (res.data.code == 200) {
              wx.setStorageSync('openid', res.data.data.openid);
              that.globalData.openid = res.data.data.openid;

              wx.setStorageSync('member_id', res.data.data.member_id);
              that.globalData.member_id = res.data.data.member_id;

              wx.setStorageSync('user_id', res.data.data.user_id);
              that.globalData.user_id = res.data.data.user_id;

              wx.setStorageSync('sessionId', res.data.data.sessionId);
              that.globalData.sessionId = res.data.data.sessionId;

              if (res.data.data.userInfo) {
                wx.setStorageSync('userInfo', res.data.data.userInfo);
                that.globalData.userInfo = res.data.data.userInfo;
              }

              typeof success == "function" && success();
            } else {
              typeof fail == "function" && fail();
            }
          },
          fail: function (res) {
            console.log(res);
          }
        })
      },
      fail: function (result) {
        console.log(result);
      }
    })
  },


  /**
 * 用户授权、用户信息更新
 */
  wxUserInfo: function (userInfo, success, fail) {
    let that = this;
    wx.request({
      url: that.getApiUrl('xcxapi/getAuth'),
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      method: 'POST',
      data: {
        userInfo: JSON.stringify(userInfo),
        member_id: that.globalData.member_id,
      },
      success: function (res) {

        let data = res.data;
        if (data.code == 200) {
          wx.setStorageSync('userInfo', userInfo);
          that.globalData.userInfo = userInfo;
          typeof success == "function" && success();
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000,
            mask: true
          })
          typeof fail == "function" && fail();
        }
      },
      fail: function () {
      }
    })
  },
  getBindData(res) {
    return res.target.dataset;
  },

  /**
     * 获取完整 API 地址
     * @param {String} uri API 的 Uri 路径
     */
  getApiUrl(uri) {
    return this.globalData.hosts + uri
  },
  getHeader() {
    return { Cookie: 'PHPSESSID=' + this.globalData.sessionId };
  },

  /**
   * get
   */
  getData(url, header = false, param = [], behavior = {}) {
    if (header) {
      header = {
        'Cookie': 'PHPSESSID=' + this.globalData.sessionId
      };
    } else {
      header = {};
    }
    wx.request({
      url: url,
      header: header,
      data: param,
      success: function (res) {
        if ('function' == typeof behavior.success) {
          behavior.success(res);
        }
      },
      fail: function (res) {
        if ('function' == typeof behavior.fail) {
          behavior.fail(res);
        } else {
          wx.showToast({
            title: '请求失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * post
   */
  postData(url, header = false, param = [], behavior = {}) {
    if (header) {
      header = {
        'Cookie': 'PHPSESSID=' + this.globalData.sessionId,
        "content-type": "application/x-www-form-urlencoded"
      };
    } else {
      header = { "content-type": "application/x-www-form-urlencoded" };
    }
    wx.request({
      url: url,
      header: header,
      data: param,
      method: 'POST',
      success: function (res) {
        if ('function' == typeof behavior.success) {
          behavior.success(res);
        }
      },
      fail(res) {
        if ('function' == typeof behavior.fail) {
          behavior.fail(res);
        } else {
          var msg = '请求失败'
          if ('undefined' !== typeof res.data) {
            msg = data.msg;
          }
          wx.showToast({
            title: msg,
            icon: 'none'
          })
        }
      }
    })
  },

  //get缓存
  getCache(key) {
    var data = wx.getStorageSync('cache_' + key);
    var now = new Date().getTime();
    if (data.expire > 0 && now > data.expire) {
      wx.removeStorageSync('cache_' + key);
      return null;
    } else {
      return data.data
    }
  },

  //set缓存 expire为秒数，不是毫秒
  setCache(key, data, expire = 0) {
    var storage = {}
    storage.data = data;
    if (expire < 0) {
      wx.removeStorageSync('cache_' + key)
    }
    storage.expire = expire > 0 ? new Date().getTime() + expire * 1000 : 0;
    wx.setStorageSync('cache_' + key, storage);
  },

  getQuery: function (options) {
    if (options.q) {
      var url = decodeURIComponent(options.q);
      var obj = {};
      if (url.indexOf('?') != -1) {
        var str = url.split('?')[1];
        var strs = str.split('&');
        for (var i = 0; i < strs.length; i++) {
          obj[strs[i].split('=')[0]] = strs[i].split('=')[1];
        }
      }
      console.log(obj);
      return obj;
    } else {
      return options;
    }
  },

  noneToast(title, time = 1000) {
    wx.hideLoading();
    wx.showToast({
      title: title,
      icon: 'none',
      duration: time,
      mask: true
    })
  },

  maskLoading(time = 1000) {
    wx.showToast({
      icon: 'loading',
      mask: true,
      duration: time,
    })
  }
});